package z;

import java.util.Stack;

/**
 * @author fangkun
 * @create 2023-01-09-11:23
 *
 * 单调栈应用
 * 获取一个数组中每个值 左边离他最近的小于他的数，右边边离他最近的小于他的数（数组元素不重复）
 */
public class NearLessNoRepeat {

    public static int[][] getNearLessNoRepeat(int[] arr){

        int[][] res = new int[arr.length][2];
        Stack<Integer> stack = new Stack<>();

        //入栈流程，栈中从底向上由小到大，改变顺序时出栈
        for (int i = 0; i < arr.length; i++) {
            while (!stack.isEmpty() && arr[stack.peek()] > arr[i]){
                int popIndex = stack.pop();
                int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();

                res[popIndex][0] = leftLessIndex;
                res[popIndex][1] = i;
            }
            stack.push(i);
        }

        //数组所有元素都入栈完成，处理栈中剩下的元素
        while (!stack.isEmpty()){
            int popIndex = stack.pop();
            int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();
            res[popIndex][0] = leftLessIndex;
            res[popIndex][1] = -1;
        }

        return res;
    }

    public static void main(String[] args) {

    }
}
